package edu.bw.controller;

import edu.bw.enums.OperationsStatus;
import edu.bw.po.Product;
import edu.bw.service.ProductService;
import edu.bw.utils.ResultUtils;
import edu.bw.vo.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 查询所有商品
     * @return json格式的操作结果
     */
    @GetMapping("/list")
    public ResponseData findAll() {
        try {
            List<Product> products = productService.findAll();
            return ResultUtils.result(OperationsStatus.SUCCESS, products);
        } catch (Exception e) {
            return ResultUtils.result(OperationsStatus.FAIL, e.getMessage());
        }
    }

    /**
     * 更新商品信息
     *
     * @param product 商品信息
     * @return json格式的操作结果
     */
    @PutMapping("/update")
    public ResponseData UpdateProduct(@RequestBody Product product) {
        try {
            productService.updateProduct(product);
            return ResultUtils.result(OperationsStatus.SUCCESS, null);
        } catch (Exception e) {
            return ResultUtils.result(OperationsStatus.FAIL, e.getMessage());
        }
    }

    /**
     * 添加商品
     *
     * @param product 要保存的商品信息
     * @return json格式的操作结果
     */
    @PostMapping("/add")
    public ResponseData addProduct(@RequestBody Product product) {
        try {
            productService.saveProduct(product);
            return ResultUtils.result(OperationsStatus.SUCCESS, null);
        } catch (Exception e) {
            return ResultUtils.result(OperationsStatus.FAIL, e.getMessage());
        }
    }

    @DeleteMapping("/delete/{pid}")
    public ResponseData deleteProduct(@PathVariable("pid") Integer pid){
        try {
            productService.deleteByPid(pid);
            return ResultUtils.result(OperationsStatus.SUCCESS,null);
        } catch (Exception e) {
            return ResultUtils.result(OperationsStatus.FAIL, e.getMessage());
        }
    }






}
